package com.sky.controller.fileupload;

import com.sky.exception.FileUpdateUnsuccss;
import com.sky.properties.AliyunOSSProperties;
import com.sky.result.Result;
import com.sky.utils.AliyunOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/admin/common")
public class FileUploadController {
    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;

    @RequestMapping("/upload")
    public Result upload(MultipartFile file) {
        try {
            //获取字节数组
            byte[] bytes = file.getBytes();
            //获取文件后缀名
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
            //获取url
            String url = AliyunOSSUtils.upload(aliyunOSSProperties.getEndpoint(),aliyunOSSProperties.getBucketName(),bytes, extName);
            return Result.success(url);
        }catch (Exception e){
            throw new FileUpdateUnsuccss("文件上传失败");
        }
    }
}
